package cn.nkpro.elcube.docengine.utils;

import cn.nkpro.elcube.exception.NkSystemException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @ Author     ：lbw
 * @ Date       ：11:00 2022/7/25
 * @ Description：
 * @ Modified By：
 */
@Slf4j
public class ZipUtils {

    public static void zipFile(File inputFile, ZipOutputStream ouputStream) throws IOException {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            if (inputFile.exists()) {
                if (inputFile.isFile()) {
                    fis = new FileInputStream(inputFile);
                    bis = new BufferedInputStream(fis, 512);
                    ZipEntry zipEntry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(zipEntry);
                    //向压缩文件中输出数据
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bis.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        if(files != null){
                            for (File file : files) {
                                zipFile(file, ouputStream);
                            }
                        }else {
                            throw new NkSystemException("下载的文件为null");
                        }
                    } catch (Exception e) {
                        log.error("根据输入的文件与输出流对文件进行打包异常！失败信息：" + e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            log.error("根据输入的文件与输出流对文件进行打包异常！失败信息：" + e.getMessage());
        } finally {
            if(null != bis){
                bis.close();
            }
            if (null != fis) {
                fis.close();
            }
        }
    }
}
